<template>
	<div class="settings-sessions -mt-4">
		<NScrollbar x-scrollable>
			<UpTable
				:options="tableOptions"
				:data="list || []"
				idKey="id"
				class="max-md:min-w-full max-md:w-max !min-h-20"
				tableClass="max-md:!w-auto">
				<template #loading>
					<BaseLoadingCircle />
				</template>
				<template #deviceType="{ data: item }">
					<span class="text-t-1">{{ item?.deviceType }} {{ item?.browserType }}</span>
				</template>
				<template #lastUsedTime="{ data: item }">
					<span v-if="item.current">{{ $t('set.session.online') }}</span>
					<NTime v-else-if="item?.lastUsedTime" :time="item?.lastUsedTime" type="relative" />
				</template>
				<template #action="{ data: item }">
					<span v-if="item.current">{{ $t('set.session.current') }}</span>
					<span
						v-else-if="item.loginStatus"
						class="text-primary app-text-react"
						@click="handleLogout(item)">
						{{ $t('set.session.logout') }}
					</span>
					<span v-else>{{ $t('set.session.loggedOut') }}</span>
				</template>
			</UpTable>
		</NScrollbar>
		<BaseMore :isFinish="isFinish" :loading="loading" @load="handleRun(false)" />
	</div>
</template>

<script setup lang="ts">
import { onBeforeUnmount, onMounted } from 'vue'
import { find } from 'lodash-es'
import { NScrollbar, NTime } from 'naive-ui'
import { getSessionList, logoutSessionById, logoutSessionOther } from '@/api/profile.ts'
import { BaseLoadingCircle, BaseMore } from '@/components/base'
import { TableOptions, UpTable } from '@/components/up'
import { useDialog, useRequest } from '@/hooks'
import { bus } from '@/utils'
import { SETTINGS_SESSIONS_LOGIN_STATUS, SETTINGS_SESSIONS_LOGOUT_OTHER } from '@/constants'

export type SessionItem = {
	address: string
	browserType: string
	current: boolean
	deviceType: string
	id: string
	ip: string
	lastUsedTime: string
	loginStatus: boolean
}
const tableOptions = <TableOptions[]>[
	{ prop: 'deviceType', textT: 'set.session.device', slot: 'deviceType' },
	{ prop: 'address', textT: 'set.session.location' },
	{ prop: 'ip', textT: 'set.session.ipAddress' },
	{ prop: 'lastUsedTime', textT: 'set.session.lastUsed', slot: 'lastUsedTime' },
	{ prop: '', textT: 'set.session.action', align: 'right', slot: 'action' }
]
const dialog = useDialog()
const { loading, isFinish, list, run } = useRequest<{ rows: SessionItem[] }>(getSessionList, {
	showError: true,
	pageSize: 10,
	paramsAlias: { page: 'pageNum' },
	resultAlias: { list: 'rows' }
})
const { run: runLogout } = useRequest(logoutSessionById, { showError: true })
const { run: runLogoutOther } = useRequest(logoutSessionOther, { showError: true })

const handleRun = async (refresh?: boolean, params?: any) => {
	// loginStatus: 全部数据 就不传，true已登录，false已退出
	await run(
		{
			// orderByColumn: 'id',isAsc: 'desc',
			loginStatus: params?.loginStatus === true ? false : null
		},
		{ refresh }
	)
}
const handleLogout = async (item: SessionItem) => {
	dialog.warning({
		titleT: 'set.session.logoutThisConfirm',
		confirmFn: async () => {
			await runLogout({ id: item.id })
			const _item = find(list.value, { id: item.id })
			_item && Object.assign(item, { loginStatus: false })
		}
	})
}
const handleLogoutOther = async () => {
	dialog.warning({
		titleT: 'set.session.logoutOtherConfirm',
		confirmFn: async () => {
			await runLogoutOther()
			await handleRun(true)
		}
	})
}

onMounted(() => {
	handleRun()
	bus.$on(SETTINGS_SESSIONS_LOGIN_STATUS, (value: boolean) =>
		handleRun(true, { loginStatus: value })
	)
	bus.$on(SETTINGS_SESSIONS_LOGOUT_OTHER, () => handleLogoutOther())
})
onBeforeUnmount(() => {
	bus.$off(SETTINGS_SESSIONS_LOGIN_STATUS)
	bus.$off(SETTINGS_SESSIONS_LOGOUT_OTHER)
})
</script>

<style scoped></style>
